package com.fnst.facedetect.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Date;

import javax.servlet.http.HttpServlet;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fnst.facedetect.dao.CommonDao;
import com.fnst.facedetect.service.GetPhotoService;
import com.fnst.facedetect.util.Utils;
import com.sun.xml.internal.messaging.saaj.util.ByteOutputStream;

import sun.misc.BASE64Decoder;

public class AbstractDetectServlet extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	protected Logger log = LoggerFactory.getLogger(getClass());
	protected CommonDao commonDao;
	protected GetPhotoService gps = new GetPhotoService();
	
	public AbstractDetectServlet(){
		super();
        try {
			commonDao = CommonDao.getInstance();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	protected String getUploadPath() {
		return getSavePath("upload");
	}
	
	protected String getSavePath1() {		
		return getSavePath("save1");
	}
	
	protected String getSavePath2() {
		return getSavePath("save2");
	}
	
	private String getSavePath(String pathName){
		String daySuffix = Utils.getDateString(new Date()) + "/"; 
		String rootPath=getClass().getResource("").getFile().toString();
		String path = rootPath.substring(0, rootPath.indexOf("WEB-INF")) + pathName + "/" + daySuffix;
		File file = new File(path);
		if(!file.exists()){
			file.mkdir();
		}
		return path;
	}
	
	protected void savePicture(String data, String path){
		if(data == null){
			return;
		}
		OutputStream out = null;
		try{
			ByteOutputStream byteOut = new ByteOutputStream();
			transport(data, byteOut);
			byte[] picByte = byteOut.getBytes();			
	        out = new FileOutputStream(path);      
	        out.write(picByte);
	        out.flush();
		}catch(Exception e){
			log.error("保存图片错误["+data+" | " + path + "]", e);
		}finally{
			if(out!=null){
				try{out.close();}catch(Exception e){};
			}
		}
	}
	
	protected boolean transport(String imgStr, OutputStream out) {
		if (imgStr == null) // 图像数据为空
			return false;
		BASE64Decoder decoder = new BASE64Decoder();
		try {
			// Base64解码
			byte[] b = decoder.decodeBuffer(imgStr);
			for (int i = 0; i < b.length; ++i) {
				if (b[i] < 0) {// 调整异常数据
					b[i] += 256;
				}
			}
			out.write(b);
			out.flush();
			out.close();
			return true;
		} catch (Exception e) {
			return false;
		}
	}
}
